
import { ConfigService } from "@nestjs/config";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy, StrategyOptions } from "passport-jwt";
import { UnauthorizedException } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";

export class JwtStrategy extends PassportStrategy(Strategy,"jwt") {
  constructor(
    private configService: ConfigService,
    private jwtService: JwtService
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: configService.get("JWT_SECRET"),
    } as StrategyOptions);
  }
  
  // 校验token
  async validate(token: string) {
    try {
      // 密钥
      const JWT_SECRET = this.configService.get("JWT_SECRET")
      // 解析token
      const userInfo = this.jwtService.verify(token, {
        secret: JWT_SECRET
      })
      return userInfo
    } catch (error) {
      throw new UnauthorizedException("token 不正确");
    }
  }

}